package com.jjlin.web.admin;

import com.jjlin.entity.Blog;
import com.jjlin.entity.User;
import com.jjlin.service.BlogService;
import com.jjlin.service.TagService;
import com.jjlin.service.TypeService;
import com.jjlin.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class BlogController {

    private static final String INPUT = "admin/blogs-input";
    private static final String LIST = "admin/blogs";
    private static final String REDIRECT_LIST = "redirect:/admin/blogs";


    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping("/blogs")
    public String blogs(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC)
                                    Pageable pageable, BlogQuery blog, Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("page",blogService.listBlog(pageable, blog));
        return LIST;
    }

    //搜索筛选博客（包括上下页功能，即点击上下页时也将筛选条件发送给后台）
    @PostMapping("/blogs/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         BlogQuery blog, Model model) {
        Page<Blog> pages = blogService.listBlog(pageable, blog);
        model.addAttribute("page", pages);
        return "admin/blogs :: blogList";//只刷新blogList（即前端表格部分）,不刷新筛选条件
    }

    @GetMapping("/blogs/input")
    public String inputPage(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
        model.addAttribute("blog", new Blog());
        return INPUT;
    }


    //跳转到博客编辑页面
    @GetMapping("/blogs/{id}/update")
    public String updateBlog(@PathVariable Long id, Model model) {
        model.addAttribute("types", typeService.listType());
        model.addAttribute("tags", tagService.listTag());
        Blog blog = blogService.getBlog(id);//获得博客内容
        blog.init();
        model.addAttribute("blog",blog);
        return INPUT;
    }

    //增加和修改博客
    @PostMapping("/blogs")
    public String inputBlog(Blog blog, RedirectAttributes attributes, HttpSession session){
        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        Blog b;
        System.out.println("createTime:" + blog.getCreateTime());
        if (blog.getId() == null) {//新增博客
            b =  blogService.saveBlog(blog);
            if (b == null ) {
                attributes.addFlashAttribute("message", "增加博客失败");
            } else {
                if(b.isPublished())
                    attributes.addFlashAttribute("message", "增加博客成功");
                else
                    attributes.addFlashAttribute("message","保存博客成功");
            }
        } else {//修改博客
            b = blogService.updateBlog(blog.getId(), blog);
            if (b == null ) {
                attributes.addFlashAttribute("message", "修改博客失败");
            } else {
                if(b.isPublished())
                    attributes.addFlashAttribute("message", "修改博客成功");
                else
                    attributes.addFlashAttribute("message","保存博客成功");
            }
        }
        return REDIRECT_LIST;
    }

    //删除博客
    @GetMapping("/blogs/delete/{id}")
    public String deleteBlog(@PathVariable Long id,RedirectAttributes attributes) {
        try{
            blogService.deleteBlog(id);
        }catch(Exception e){
            attributes.addFlashAttribute("message", "删除博客失败");
            return REDIRECT_LIST;
        }
        attributes.addFlashAttribute("message", "删除博客成功");
        return REDIRECT_LIST;
    }


}
